package com.sample.controller;

import com.sample.service.YahooExchangeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Currency;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

/**
 * Created by leo.na on 21/03/2017.
 */
@RestController
public class KresnaApiController {

    @Autowired
    private YahooExchangeService yahooExchangeService;

    @GetMapping(value = "/exchangeRate", produces = APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResponseEntity getExchangeRate(
            @RequestParam("from") String from,
            @RequestParam("to") String to
    ) {
        // check inputs
        Currency fromCurrency = yahooExchangeService.getCurrencyByCode(from);
        if (fromCurrency == null) return RestResponse.badRequest("Invalid currency [" + from + "]");
        Currency toCurrency = yahooExchangeService.getCurrencyByCode(to);
        if (toCurrency == null) return RestResponse.badRequest("Invalid currency [" + to + "]");

        return RestResponse.ok("Yahoo Exchange rate from [" + from + "] to [" + to + "]", yahooExchangeService.getLiveRate(fromCurrency, toCurrency));
    }

}
